package com.ecsolutions.controller;

import com.ecsolutions.entity.User_Entity;
import com.ecsolutions.service.User_Service;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;

@Controller
public class MainPage {

    private static final Logger logger = LoggerFactory.getLogger(MainPage.class);
    private String userid;

    @Autowired
    private User_Service user_service;

    @GetMapping("/lor")
    public String getMainPage(@RequestParam String userid) {
        this.userid = userid;
        return "mainPage";
    }

    //获取用户信息
    @RequestMapping(value = "/lor/getUser")
    @ResponseBody
    public JSONObject getUser() {
        User_Entity currentUser = user_service.getUserInfo(userid);
        HashMap<String, Object> messageMap = new HashMap<String, Object>();
        messageMap.put("userid", userid);
        messageMap.put("username", currentUser.getUsername());
        messageMap.put("userrole", JSONArray.fromObject(user_service.getUserRoleInfoList(userid)));
        JSONObject result = JSONObject.fromObject(messageMap);
        return result;
    }

    @GetMapping("/login")
    public String getLoginPage(Model model) {
        model.addAttribute("employee_entity", new User_Entity());
        return "login";
    }

    @PostMapping("/login")
    public String postLoginPage(Model model, @ModelAttribute("employee_entity") User_Entity employee_entity,RedirectAttributes redirectAttributes) {
//        if (result.hasErrors()) {
//            model.addAttribute("employee_entity", employee_entity);
//            return "redirect:/login";
//        }
        String employeename = employee_entity.getUsername();
        logger.info(employee_entity.getPasswrd());
        UsernamePasswordToken token = new UsernamePasswordToken(employeename, employee_entity.getPasswrd());
        Subject currentUser = SecurityUtils.getSubject();
        try {
            logger.info("对用户[" + employeename + "]进行登录验证..验证开始");
            currentUser.login(token);
            logger.info("对用户[" + employeename + "]进行登录验证..验证通过");
            if (currentUser.isAuthenticated()) {
                return "redirect:/lor?userid=" + user_service.getByUserName(employee_entity.getUsername()).getUserid();
            }
        } catch (UnknownAccountException UnknownAccount) {
            logger.info("对用户[" + employeename + "]进行登录验证..验证未通过,未知账户");
//            redirectAttributes.addFlashAttribute("message", "未知账户");
        } catch (IncorrectCredentialsException WrongPassword) {
            logger.info("对用户[" + employeename + "]进行登录验证..验证未通过,密码错误");
//            redirectAttributes.addFlashAttribute("message", "密码不正确");
        } catch (LockedAccountException LockedAccount) {
            logger.info("对用户[" + employeename + "]进行登录验证..验证未通过,账户已锁定");
//            redirectAttributes.addFlashAttribute("message", "账户已锁定");
        } catch (ExcessiveAttemptsException TooManyTimes) {
            logger.info("对用户[" + employeename + "]进行登录验证..验证未通过,错误次数过多");
//            redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数过多");
        } catch (AuthenticationException authenticationException) {
            logger.info("对用户[" + employeename + "]进行登录验证..验证未通过---");
//            redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
        }
        token.clear();
        return "redirect:/login";
    }

    @ResponseBody
    @RequestMapping(value = "/logout",produces = "text/html",method = RequestMethod.GET)
    public String logout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "success";
    }

}
